import { ADD_CART } from "../content";
import { EDIT_CART } from "../content";

const initCartList = [];
const cartlist = (state = initCartList, action) => {
    const { type, data } = action;
    switch (type) {
        case ADD_CART:
            const { id } = data;
            const index = state.findIndex((val) => val.id === id);
            if (index !== -1) {
                state[index].num++;
                return [...state];
            }
            else {
                const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
                var result = "";//接收生成好的随机数
                for (var i = 0; i < 24; i++) {
                    result += arr[Math.floor(Math.random() * 16)];
                }
                data.cartId = result;
                /*end*/
                return [...state, data];
            }
        case EDIT_CART:
            return [...data]
        // const editId = data.id;
        // const editIndex = state.findIndex((val) => val.id === editId);
        // const { type } = data;
        // if (type === 1) {
        //     state[editIndex].num++;
        //     return [...state];
        // }
        // else {
        //     if (state[editIndex].num > 1) {
        //         state[editIndex].num--;
        //         return [...state];
        //     }
        //     else {
        //         return [...state];
        //     }
        // }
        default: return state;
    }
}
export default cartlist;